<%@ include file="/WEB-INF/jspf/tag-libraries.jspf"%>
<%@ taglib tagdir="/WEB-INF/tags" prefix="tf" %>
<%@ taglib uri="http://displaytag.sf.net" prefix="display"%>
<ttjhome:bundle basename="candidates/candidates" />
<ttjhome:resource basename="candidates/candidates" bundle="errorBundle" scope="request" />
<ttjhome:rewrite var="createURL" action="/candidates/create.do?action=create" form="true" />
<ttjhome:rewrite var="editURL" action="/candidates/edit.do?action=edit" form="true"/>
<ttjhome:rewrite var="tagsURL" action="/tags.do?action=getAllTags" form="false"/>
<ttjhome:rewrite var="deleteResumeURL" action="/resume.do?action=delete" form="false"/>
<ttjhome:rewrite var="applyURL" action="/candidates/apply.do?action=apply" form="false"/>
<ttjhome:rewrite var="viewActivitiesURL" action="/candidates/activity.do?action=listActivities" form="false"/>
<ttjhome:rewrite var="closeActivityURL" action="/candidates/activity.do?action=closeActivity" form="false"/>
<ttjhome:rewrite var="newProgressURL" action="/candidates/activity.do?action=newProgress" form="false"/>
<tiles:useAttribute name="genderList" />

<c:set var="action" value="${candidateForm.map.filter}"/>
<script type="text/javascript">

function saveCandidate(){
	drawLoading();

	$("#candidateSaveForm").submit();
}

$(function() {
	$( "#candidate_birthday" ).datepicker({
		changeMonth: true,
		changeYear: true,
		showOtherMonths: true,
		selectOtherMonths: true
	});
	$( "#candidate_workfrom" ).datepicker({
		changeMonth: true,
		changeYear: true,
		showOtherMonths: true,
		selectOtherMonths: true
	});
	
	$( "#newProgressDate" ).datepicker({
			changeMonth: true,
			changeYear: true
		});
	
	$("#view-activities" )
	.button()
	.click(function() {
		//get activities
		 var url = "${viewActivitiesURL}"; 
		 url+="&candidateID="+${candidateForm.map.candidateID};
		  $.getJSON(url,function(json){
		        if (json.result == 0) {
		        		$.generateActivityContainer(json);
		  		
				}
				 else {
		            alert("error when getting activities");
		        }
		}); 
		
	});
	
	$.newProgress = function(companyName, jobName, activityId) {
		$("#inputActivityId").val(activityId);
		$("#dialog-newprogress" ).dialog( "open","option");
	}
	
	$("#dialog-newprogress" ).dialog({
		autoOpen: false,
		height: 300,
		width: 400,
		modal: true,
		
		buttons: {
			"Add": function() {
				var activityId = $("#inputActivityId").val();
					
				var url = "${newProgressURL}";
				var progressDate =$("#newProgressDate").val();
				var status =$("#newProgressStatus").val();
				var comments =$("#comments").val();
				url=url+"&activityId="+activityId+"&newProgress="+description;
				  $.getJSON(url, function(json){
				        if (json.result == 0) {
				        	$.generateActivityContainer(json);
				        		
						}
						 else {
				            alert("error when adding new progress jobs");
				           
						 }
					});
				  $( this ).dialog( "close" );
				
			},
			Cancel: function() {
				$("#inputActivityId").val("");
				
				$( this ).dialog( "close" );
			}
		}
	});
	function IgnoreSpaces(Str){
    var ResultStr = "";
    Temp=Str.split(" ");
    for(i = 0; i < Temp.length; i++){
    ResultStr +=Temp[i];
    }
    	return ResultStr;
	} 
	

	$.generateActivityContainer=function(json){
		var content = '';
		
		$('#activities-contain').empty();
		content+='<table cellpadding="0" cellspacing="0" border="0" style="display" id="activitiesTable">'
		content+='<thead>';
		content+='<tr>';
		content+='<th>CompanyAndJob</th>';
		content+='<th>RecordTime</th>';
		content+='<th>ActivityTime</th>';
		content+='<th>Status</th>';
		content+='<th>Comments</th>';
		content+='</tr>';
		content+='</thead>';
		content+='<tbody id="activitiesBody">';
		$.each(json.data, function(id, activity){
			$.each(activity.records,function(id,record){
				content +='<tr class="gradeX">';
				var link = "$.newProgress(\'" + activity.companyName + "\',\'" + activity.jobName + "\',\'" + activity.id + "\')";
				content +='<td>'+'Company Name:'+activity.companyName+' Job Name: '+activity.jobName+' <a style ="float:right"  href=# onclick=' + link + '>' + 'Add </a></td>';
				content +='<td>'+record.recordTime+ '</td>';
				content +='<td>'+record.recordTime+ '</td>';
				content +='<td>'+activity.status+ '</td>';
				content +='<td>'+record.record+ '</td>';
				content += '</tr>';
			});
		});
		content+='</tbody>';
		content+='</table>';
		
		$("#activities-contain").html(content);
		$('#activitiesTable').dataTable({
					"fnDrawCallback": function ( oSettings ) {
						if ( oSettings.aiDisplay.length == 0 )
						{
							return;
						}
						
						var nTrs = $('tbody tr', oSettings.nTable);
						var iColspan = nTrs[0].getElementsByTagName('td').length;
						var sLastGroup = "";
						for ( var i=0 ; i<nTrs.length ; i++ )
						{
							var iDisplayIndex = oSettings._iDisplayStart + i;
							var sGroup = oSettings.aoData[ oSettings.aiDisplay[iDisplayIndex] ]._aData[0];
							if ( sGroup != sLastGroup )
							{
								var nGroup = document.createElement( 'tr' );
								var nCell = document.createElement( 'td' );
								nCell.colSpan = iColspan;
								nCell.className = "group";
								nCell.innerHTML = sGroup;
								nGroup.appendChild( nCell );
								nTrs[i].parentNode.insertBefore( nGroup, nTrs[i] );
								sLastGroup = sGroup;
							}
						}
					},
					"aoColumnDefs": [
						{ "bVisible": false, "aTargets": [ 0 ] }
					],
					"aaSortingFixed": [[ 0, 'asc' ]],
					"aaSorting": [[ 1, 'asc' ]],
					"sDom": 'lfr<"giveHeight"t>ip'
					
				});
	
	};

	$.deleteResume = function(resumeId) {
		  var url = "${deleteResumeURL}";
		  url +="&id="+resumeId;
			var json = $.getJSON(url, function(json){
	             if (json.result == 0) {
	                $.each(json.data, function(id, resume){
	                	$("#resumes").empty();
	                	$("#uploadedResumes").empty();
	                	$("#uploadedResumesNames").empty();
	            		var deleteResume= "$.deleteResume(\'" + resume.id+ "\')";
	                    var str  = "<li class=\"tagit-choice\">\n"; 
	                        str += "<a href="+resume.url+">"+resume.filename+"</a>" + "\n";
	                        str += "<a class=\"close\" href=# onclick=" +deleteResume+">x</a>\n";
	            		    str += "</li>\n";
	            		document.getElementById("resumes").innerHTML +=str;
	            		document.getElementById("resumes").innerHTML +="&nbsp&nbsp";
	            		var str2="<input type='hidden' name='uploadedResumes' value='" + resume.url + "' >" ;
	            		document.getElementById("uploadedresumes").innerHTML +=str2;
	            		var str3="<input type='hidden' name='uploadedResumesNames'  value='" + resume.filename + "' >" ;
	            		document.getElementById("uploadedresumes").innerHTML +=str3;
	                  	
					});
	            }
	            else {
	                
	            }
	        });
	};
	
	$.renderResumes =function(resume){ 

	}

	
});

function drawLoading() {
	$("#loadingBox").css({
		"height": $(window).height()+ 'px',
		"display": "inline"
	});
	

	$("#loadingDialog").css({
		"top": ($(window).scrollTop() + ($(window).height() / 2)) + 'px'
	});
}

$(document).ready(function() {
  $('#file_upload').uploadify({
    'uploader'  : '../include/js/uploadify.swf',
    'script'    : 'upload',
    'cancelImg' : '../include/img/cancel.png',
    'folder'    : '/upload',
    'auto'      : true,
	onComplete: function (event, queueID, fileObj, response, data){
		var str="<a href="+response+">"+fileObj.name+"</a>";
		document.getElementById("resumes").innerHTML +=str;
		document.getElementById("resumes").innerHTML +="&nbsp&nbsp";
		var str2="<input type='hidden' name='uploadedResumes' value='" + response + "' >" ;
		document.getElementById("uploadedresumes").innerHTML +=str2;
		var str3="<input type='hidden' name='uploadedResumesNames' value='" + fileObj.name + "' >" ;
		document.getElementById("uploadedresumes").innerHTML +=str3;
  	}
  });

	
  <c:if test="${not empty uploadedResumes}">
	  document.getElementById("resumes").innerHTML="";
	  document.getElementById("uploadedresumes").innerHTML="";
	<c:forEach var="resume" items="${uploadedResumes}" >
				var deleteResume= "$.deleteResume(\'" + ${resume.id}+ "\')";
        var str  = "<li class=\"tagit-choice\">\n"; 
            str += "<a href="+'${resume.url}'+">"+'${resume.filename}'+"</a> \n";
            str += "<a class=\"close\" href=# onclick=" +deleteResume+">x</a>\n";
		    str += "</li>\n";
		document.getElementById("resumes").innerHTML +=str;
		document.getElementById("resumes").innerHTML +="&nbsp&nbsp";
		var str2="<input type='hidden' name='uploadedResumes' value=" + '${resume.url}' + " >" ;
		document.getElementById("uploadedresumes").innerHTML +=str2;
		var str3="<input type='hidden' name='uploadedResumesNames'  value=" + '${resume.filename}' + ">" ;
		document.getElementById("uploadedresumes").innerHTML +=str3;
			
	</c:forEach>
  </c:if>

  	   var url = "${tagsURL}";
		$.getJSON(url, function(json){
	        if (json.result == 0) {
				   if (json.data != null) {
				   var arr = new Array();
					   	  <c:if test="${not empty tags}">
					   	  	
		 							<c:forEach var="ff" items="${tags}" >
										arr.push("${ff.tag}");
									</c:forEach>
	 							 </c:if>
	 							
		            		$("#candidatetags").tagit({
		            			availableTags: json.data,
		            			candidatesTags:arr
		            		});
	            }
	        }
	        else {
	            alert("error when getting tags");
	        }
	    });
  
  <c:if test="${not empty  candidateForm.map.candidateBirthday}">
  		$( "#candidate_birthday" ).datepicker("setDate",'${candidateForm.map.candidateBirthday}' );
  </c:if>
  <c:if test="${not empty  candidateForm.map.candidateWorkFrom}">
	$( "#candidate_workfrom" ).datepicker("setDate",'${candidateForm.map.candidateWorkFrom}' );
   </c:if>

	var jobId = $.query.get("jobId");
	if(jobId != null){
		$("#apply").show();
	}
	
	$("#apply" )
	.button()
	.click(function() {
		//clear first 
		var jobId = $.query.get("jobId");
		if(jobId == null){
			return;
		}
		 var url = "${applyURL}";
		 url+="&jobId="+jobId;
		   <c:if test="${not empty  candidateForm.map.candidateID}">
			url+="&candidateID="+${candidateForm.map.candidateID};
		 </c:if>
		 
		 $("#apply" ).hide();
		  $.getJSON(url, function(json){
		        if (json.result == 0) {
		        	$.generateActivityContainer(json);
				}
				 else {
		            alert("error when applying jobs");
		        }
			});
	});

}




);
</script>



<div class="toolBody">
		<div class="candidatesH2">
			<h2>
				<c:choose>
					<c:when test="${action==Constants.KEY_FILTER_EDIT}"><fmt:message key="edit.candidate.title"/> (${candidateForm.map.candidateName})</c:when>
					<c:otherwise><fmt:message key="create.candidate.title"/></c:otherwise>
				</c:choose>				
			</h2>
			<div class="clear"></div>
		</div>	
		<div id="error" class="couponErrMsg">
			<tiles:insert definition="errors-page-header">
				<tiles:put name="errorStyle" value="err-msg" />
				<tiles:put name="errorIcon" value="/include/img/error-sign-sm.gif" />
			</tiles:insert>
		</div>
		<c:set var="actionURL" value="${createURL}"/>
		<c:if test="${action==Constants.KEY_FILTER_EDIT}">
			<c:set var="actionURL" value="${editURL}"/>
		</c:if>
		<html:form method="post" action="${actionURL}" styleClass="candidateEditForm"  styleId="candidateSaveForm">
		<html:hidden property="candidateID" styleId="candidateID"/>
		<div class="clear5"></div>
		
			<div class="leftCol">
			<fmt:message key="candidate.name" var="candidateName"/>
			<tf:input errorClass="err" name="candidateName"/>
			<h3><label for="candidateName" class="${err}">${candidateName}</label> </h3>
			<div class="candidateEditLable">
				<html:text property="candidateName"   maxlength="20"/>
			</div>
		</div>
		<div class="rightCol">
			<fmt:message key="candidate.gender" var="candidateGender"/>
			<tf:input errorClass="err" name="candidateGender"/>
			<h3><label for="candidateGender" class="${err}">${candidateGender}</label> </h3>
			<div class="candidateEditLable ">
				<html:select  property="candidateGender" >
					<option value=""><fmt:message key="candidate.gender.choose"/></option>
					<html:options collection="${Constants.ATTR_GENDER_LIST}" labelProperty="name" property="name"/>
				</html:select>
			</div>
		</div>
		<div class="clear5"></div>
		<div class="leftCol">
			<fmt:message key="candidate.mailbox" var="candidateMailBox"/>
			<tf:input errorClass="err" name="candidateMailBox"/>
			<h3><label for="candidateMailBox" class="${err}">${candidateMailBox}</label> </h3>
			<div class="candidateEditLable">
				<html:text property="candidateMailBox"   maxlength="30"/>
			</div>
		</div>
		
		<div class="rightCol">
			<fmt:message key="candidate.birthday" var="candidateBirthday"/>
			<tf:input errorClass="err" name="candidateBirthday"/>
			<h3><label for="candidateBirthday" class="${err}">${candidateBirthday}</label> </h3>
			<div class="candidateEditLable">
				<input id="candidate_birthday" name="candidateBirthday" type="text" />
			</div>
		</div>
		<div class="clear5"></div>
		<div class="leftCol">
			<fmt:message key="candidate.workFrom" var="candidateWorkFrom"/>
			<tf:input errorClass="err" name="candidateWorkFrom"/>
			<h3><label for="candidateWorkFrom" class="${err}">${candidateWorkFrom}</label> </h3>
			<div class="candidateEditLable">
				<input id="candidate_workfrom" name="candidateWorkFrom" type="text" />
			</div>
		</div>
		
		<div class="rightCol">
			<fmt:message key="candidate.id" var="candidateIDNumber"/>
			<tf:input errorClass="err" name="candidateID"/>
			<h3><label for="candidateIDNumber" class="${err}">${candidateIDNumber}</label> </h3>
			<div class="candidateEditLable">
				<html:text property="candidateIDNumber"   maxlength="30"/>
			</div>
		</div>
		
		<div class="clear5"></div>
		
		<div class="leftCol">
			<fmt:message key="candidate.resumes" var="candidateResumes"/>
			<tf:input errorClass="err" name="candidateResumes"/>
			<h3><label for="candidateResumes" class="${err}">${candidateResumes}</label> </h3>
			<div class="candidateEditLable">
				<input id="file_upload"  name="file_upload"  type="file"/>
			</div>
		</div>

		<div class="rightCol">
			<fmt:message key="candidate.uploaded.resumes" var="candidateUploadedResumes"/>
			<div id="resumes"></div>
			<div id="uploadedresumes"></div>
				
		</div>
		<div class="clear5"></div>
		<div class="line">
			<label for="tags">Tags</label>
			<ul id="candidatetags"></ul>
		</div>
		<div class="clear5"></div>
		<div class="candidateEditSave">
			<html:hidden property="filter"/>
		</div>
		<div class="candidateEditSave">
			<fmt:message key="save.candidate.button" var="saveCandidateButton"/>
			<input name="Save" type="button" value="${saveCandidateButton}" onclick="saveCandidate();" />
			
		</div>
		<div id="loadingBox" class="pageMaskBox">
			<div class="pageMask">
				<!--[if lt IE 7]>
				<iframe class="maskIframe"></iframe>
				<![endif]-->
			</div>
			<div id="loadingDialog" class="loadingDialog">
				<p><img src="../include/img/loading.gif"/></p>
				<p><fmt:message key="loading.text"/></p>
			</div>
		</div>
		</html:form>
	
		<div  class="candidateEditSave">
			<button id="apply" style="float:right;display:none">Apply</button>
		</div>
		<div class="clear5"></div>
		<div id="viewActivities" >
			<button id="view-activities" >View Activities</button>
		</div>
		<div class="clear5"></div>
		<div id="activities-contain" class="ui-widget" >
			
		</div>
		
		<div class="clear5"></div>
		<div id="dialog-newprogress" title="Add new progress">
			<div><p>Date: <input type="text" id="newProgressDate" /></p></div>
			<div>
			<label for="status">Status</label>
			<select id="newProgressStatus" >
			 <Option value="Recommend">Recommend</option>
			 <Option value="Interview">Interview</option>
			 <Option value="Onboard">Onboard</option>
			 <Option value="Closed">Closed</option>
			 <Option value="Others">Others</option>
			</select>
			</div>
			<div>
			<label for="comments">Comments</label>
			<input type="text" name="comments" id="comments" class="text ui-widget-content ui-corner-all" />
			</div>
		</div>
		
		<input type="hidden" id="inputActivityId" value=""/>
		

</div>
